import _ from 'lodash-es'
import type { FormConfigSubmit } from './types'
import type { FormConfigBaseInfo } from './components/BaseInfo/config'
import type { FormConfigBaseForm } from './components/BaseForm/config'
import { component as baseInfoCoomponent } from './components/BaseInfo/config'
import { component as baseFormCoomponent } from './components/BaseForm/config'

const emptyObj = {}

function handleStrToObj(str: any, replace = {}): object {
  let result = replace
  try {
    if (str && typeof str === 'string') {
      result = JSON.parse(str)
    }
  } catch (err) {
    result = replace
  }
  return result
}

export class FormConfigBuild implements FormConfigBaseInfo {
  id: string
  name: string
  description: string
  sort: number
  configJson: FormConfigBaseForm

  constructor(config: FormConfigSubmit | undefined) {
    this.id = config && config?.id || baseInfoCoomponent.property.id
    this.name = config && config?.name || baseInfoCoomponent.property.name
    this.description = config && config?.description || baseInfoCoomponent.property.description
    this.sort = config && config?.sort || baseInfoCoomponent.property.sort
    this.configJson = this.buildBaseForm(config)
  }

  buildBaseForm(config: FormConfigSubmit | undefined): FormConfigBaseForm {
    const newConfig = config ? handleStrToObj(config.configJson, emptyObj) : emptyObj
    const configJson = _.merge({}, baseFormCoomponent.property, newConfig) as FormConfigBaseForm
    return configJson
  }
}
